package com.ecric.http.socket;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;

/**
 * <h3>Description</h3>
 * TODO
 * <h3>Author</h3> Eric
 * <h3>Date</h3> 2017/9/16 11:38
 * <h3>Copyright</h3> Copyright (c)2017 Shenzhen TLKY  Co., Ltd. Inc. All rights reserved.
 */
public class ClientThread implements Runnable {
    private Handler handler;
    private Socket socket;
    //输入流 读取服务端传送过来的消息
    private BufferedReader br;
    //输出流往服务器发送信息
    private static OutputStream outputStream;
    public static Handler  revHandler ;
    private InputStream inputStream;
    //计时器
    private Timer timer  = new Timer();

    public ClientThread(Handler handler) {
        this.handler = handler;
    }
    @Override
    public void run() {
        try {
            //192.168.11.139 为本地电脑的ip
            socket = new Socket("192.168.11.139",30010);
//            socket.setKeepAlive(true);
            inputStream = socket.getInputStream();
            br = new BufferedReader(new InputStreamReader(inputStream));
            outputStream = socket.getOutputStream();
            Log.e("进入循环线程：","-------------->");

            /**
             *
             * 开子线程读取数据，因为readLine()会导致阻塞
             * 对于socket，不能认为把某次写入到流中的数据读取完了就算流结尾了，
             * 但是socket流还存在，还可以继续往里面写入数据然后再读取。
             * 这时用BufferedReader封装socket的输入流，调用BufferedReader的readLine方法是不会返回null的
             * 所以在循环内如果不判断   content!=null && content.length() > 0  那么程序将会一直阻塞在这里(程序是因为readLine阻塞,并不是死循环)
             *
             */
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Log.e("开始读取：","1111");
                    String content  = null;
                    try {
                        while (((content = br.readLine()) != null) && (content.length() > 0)){
                            Log.e("读取====》",content);
                            //每当有消息时，及时通知主界面更新消息
                            Message  message  = new Message();
                            message.what = 0x123;
                            message.obj  = content;
                            handler.sendMessage(message);
                        }
                    } catch (IOException e) {
                        closeSocket();
                        e.printStackTrace();
                    }
                }
            }).start();

//            timer.schedule(new TimerTask() {
//                @Override
//                public void run() {
//                    String content  = null;
//                    try {
//                        Log.e("开始读取22：","1111");
//                        while ((content = br.readLine()) != null){
//                            Log.e("读取====》",content);
//                            //每当有消息时，及时通知主界面更新消息
//                            Message  message  = new Message();
//                            message.what = 0x123;
//                            message.obj  = content;
//                            handler.sendMessage(message);
//                        }
//                    } catch (IOException e) {
//                        closeSocket();
//                        e.printStackTrace();
//                    }
//                }
//            },0,5000);

            Looper.prepare();
            revHandler = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    if (msg.what == 0x345){
                        try {
                            outputStream.write((msg.obj.toString() + "\r\n").getBytes("utf-8"));
                            Log.e("写入====》",msg.obj.toString());
                            outputStream.flush();
                        } catch (UnsupportedEncodingException e) {
                            closeSocket();
                            e.printStackTrace();
                        } catch (IOException e) {
                            closeSocket();
                            e.printStackTrace();
                        }
                    }
                }
            };
            //把当前的线程初始化为looper//，循环读取服务端发过来的消息
            Looper.loop();
        } catch (IOException e) {
            closeSocket();
            e.printStackTrace();
        }
    }


    /**
     * 关闭端口
     */
    private void  closeSocket(){
            try {
                if (null != inputStream){
                   inputStream.close();
                }
                if (null != outputStream){
                    outputStream.close();
                }
                if (null != br){
                    br.close();
                }
                if (null != socket){
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
}
